//
//  WPHomeEditeImageVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/11.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPHomeEditeImageVC.h"
#import "WPHomeEditeCollectionCell.h"
#import "WPScratchCardView.h"
#import "UIImage+AsyncDraw.h"
#import <CoreImage/CoreImage.h>
#import <OpenGLES/EAGL.h>

#define minScale  1.0
#define maxScale  2.5

@interface WPHomeEditeImageVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraints;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)WPHomeEditeCollectionCell *selectedCell;
@property (strong, nonatomic) WPScratchCardView *imageBgView;
@property(nonatomic,strong)NSMutableArray *snapImagesArr;
@property(nonatomic,strong)UIImage *currentImage;
@property(nonatomic,strong)NSMutableArray *changedArr;

@property(nonatomic,strong)CIFilter *filter;
@property(nonatomic,strong)CIContext *context;
@property(nonatomic,strong)NSMutableDictionary *filterDescriptorsDict;

@property(nonatomic,assign)CGFloat totalScale;
@property(nonatomic,assign)CGPoint oldCenter;

@property(nonatomic,strong)UIImageView *guideMosaicImageView;

@end

static NSString *ID = @"image";
@implementation WPHomeEditeImageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    
    self.leftConstraints.constant = (SCREEN_WIDTH-68*2)/3;
    self.rightConstraint.constant = (SCREEN_WIDTH-68*2)/3;
    
    self.currentImage = self.selectedPhotos[0];
    [self setupImageBgView:self.currentImage frame:[self caculatorImageFrame:self.currentImage]];
    
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    [self.collectionView registerClass:[WPHomeEditeCollectionCell class] forCellWithReuseIdentifier:ID];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self.collectionView reloadData];
    [self collectionView:self.collectionView didSelectItemAtIndexPath:self.selectedIndexPath];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //        第一次使用
    
    NSInteger masoicCount = [[NSUserDefaults standardUserDefaults] integerForKey:mosaicCount];
    
    if(masoicCount <= 3)
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirst_Mosaic];
        
        [[NSUserDefaults standardUserDefaults] setInteger:masoicCount+1 forKey:mosaicCount];
        
        //        判断是不是第一次使用
        NSString *name = nil;
        if (SCREEN_WIDTH < 375)
        {
            name = @"isFirst_Mosaic5";
        }
        else if (SCREEN_WIDTH < 414)
        {
            name = @"isFirst_Mosaic6";
        }
        else
        {
            name = @"isFirst_Mosaic6p";
        }
        UIImageView *guideImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:name]];
        self.guideMosaicImageView = guideImageView;
        guideImageView.userInteractionEnabled = YES;
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:guideImageView];
        
        [guideImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(keyWindow);
        }];
        
        UITapGestureRecognizer *TGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideImageViewDidClick:)];
        [guideImageView addGestureRecognizer:TGR];
    }
}

-(void)guideImageViewDidClick:(UITapGestureRecognizer *)tgr
{
    [self.guideMosaicImageView removeFromSuperview];
}


-(void)setSelectedPhotos:(NSMutableArray *)selectedPhotos
{
    _selectedPhotos = selectedPhotos;
    
    for (int i = 0; i < selectedPhotos.count; i++)
    {
        UIImage *image = selectedPhotos[i];
        
//        self.filter = [CIFilter filterWithName:@"CISharpenLuminance"];
//        //将image转换成CIImage;
//        CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
//        [self.filter setValue:inputImage forKey:kCIInputImageKey];
//        
//        //  饱和度      0---2
////      [self.filter setValue:[NSNumber numberWithFloat:0.5] forKey:@"inputSaturation"];
//        //  亮度  10   -1---1
////        [self.filter setValue:[NSNumber numberWithFloat:0.5] forKey:@"inputBrightness"];
////          对比度 -11  0---4
////        [self.filter setValue:[NSNumber numberWithFloat:2.0] forKey:@"inputContrast"];
//        
//        //输出渲染之后的CIImage
//        CIImage *outImage = self.filter.outputImage;
//        //创建像素位图
//        CGImageRef resultImage = [self.context createCGImage:outImage fromRect:outImage.extent];
//        UIImage *firstImage = [UIImage imageWithCGImage:resultImage];
//        
//        
//        self.filter = [CIFilter filterWithName:@"CIColorControls"];
////        //将image转换成CIImage;
//        CIImage *secondInputImage = [CIImage imageWithCGImage:firstImage.CGImage];
//        [self.filter setValue:secondInputImage forKey:kCIInputImageKey];
//        //        //  亮度  10   -1---1
//        [self.filter setValue:[NSNumber numberWithFloat:0.1] forKey:@"inputBrightness"];
//        //  对比度 -11  0---4
//        [self.filter setValue:[NSNumber numberWithFloat:1.5] forKey:@"inputContrast"];
//        //输出渲染之后的CIImage
//        CIImage *secondOutImage = self.filter.outputImage;
//        //创建像素位图
//        CGImageRef secondResultImage = [self.context createCGImage:secondOutImage fromRect:outImage.extent];
//        UIImage *secondImage = [UIImage imageWithCGImage:secondResultImage];

        selectedPhotos[i] = image;
        
//        CGImageRelease(resultImage);//释放CGImage对象
    }
    
    [self.changedArr addObjectsFromArray:selectedPhotos];
    
    for (UIImage *image in selectedPhotos)
    {
        [self.snapImagesArr addObject:[UIImage thumbnailWithImageWithoutScale:image size:CGSizeMake(48, 48)]];
    }
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.selectedPhotos.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WPHomeEditeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.littleImage = self.snapImagesArr[indexPath.item];
    cell.backgroundColor = RGB_SAME(51);
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.imageBgView.isMosaic)
    {
        [self save];
    }
    
    WPHomeEditeCollectionCell *cell = (WPHomeEditeCollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    self.selectedCell.backgroundColor = RGB_SAME(51);
    self.selectedCell = cell;
    self.selectedCell.backgroundColor = GlobalColor;
    
    self.selectedIndexPath = indexPath;
    
    if (self.imageBgView)
    {
        self.imageBgView.transform  = CGAffineTransformIdentity;
        
        [self.imageBgView clear];
        UIImage *image = self.changedArr[indexPath.item];
        [self setupImageBgView:image frame:[self caculatorImageFrame:image]];
        [self.imageBgView setNeedsDisplay];
    }
}

-(void)setupImageBgView:(UIImage *)image frame:(CGRect)frame
{
    [self.imageBgView removeFromSuperview];
    self.imageBgView = [[WPScratchCardView alloc] initWithFrame:frame];
    self.imageBgView.surfaceImage = image;
    [self.view addSubview:self.imageBgView];
    
    self.oldCenter = self.imageBgView.center;
}

- (CGRect)caculatorImageFrame:(UIImage *)image
{
    if (image) {
        
        CGFloat fixedHeight = (SCREEN_HEIGHT-69-107);
        
        CGFloat imageH = 0.0;
        CGFloat imageW = 0.0;
        if (image.size.height > image.size.width)
        {
            imageH = fixedHeight;
            imageW = imageH*image.size.width/image.size.height;
        }
        else if (image.size.height < image.size.width)
        {
            imageW = SCREEN_WIDTH;
            imageH = image.size.height*imageW/image.size.width;
        }
        else
        {
            imageW = SCREEN_WIDTH;
            imageH = imageW;                                   
        }
        
        CGFloat x = (SCREEN_WIDTH-imageW)/2;
        CGFloat y = 107 + (fixedHeight-imageH)/2;
        
        return CGRectMake(x, y, imageW, imageH);
    }
    return CGRectZero;
}

- (IBAction)clear
{
    self.imageBgView.transform = CGAffineTransformIdentity;
    
//    [self.imageBgView clear];
    
    [self.imageBgView clear];
    UIImage *image = self.selectedPhotos[self.selectedIndexPath.item];
    [self setupImageBgView:image frame:[self caculatorImageFrame:image]];
    [self.imageBgView setNeedsDisplay];
    
    self.changedArr[self.selectedIndexPath.item] = self.selectedPhotos[self.selectedIndexPath.item];
    
    [self.collectionView reloadData];
}

- (void)save
{
    NSIndexPath *indexPath = self.selectedIndexPath;
    
//    self.imageBgView.transform = CGAffineTransformIdentity;
//    self.imageBgView.center = self.oldCenter;
    
    UIImage *newImage = [self.imageBgView save];
    
    if(newImage)
    {
//        [self showSuccessInfoWithStatus:@"保存成功"];
    }
    else
    {
//        [self showErrorInfoWithStatus:@"保存失败"];
    }
    
    UIImage *oldImage = self.changedArr[indexPath.item];
    
    self.changedArr[indexPath.item] = [self OriginImage:newImage scaleToSize:oldImage.size];
}


- (IBAction)back
{
    if (self.imageBgView.isMosaic)
    {
        [self save];
    }
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.imageBgView.transform = CGAffineTransformIdentity;
    self.imageBgView.center = self.oldCenter;
    
    [self.selectedPhotos removeAllObjects];
    [self.selectedPhotos addObjectsFromArray:self.changedArr];
    
    if (self.editeImageHandle)
    {
        NSMutableArray *scaleImagesArr = [NSMutableArray array];
        for (UIImage *image in self.selectedPhotos)
        {
            NSData *data = UIImageJPEGRepresentation(image, 0.6);
            UIImage *newImage = [UIImage imageWithData:data];
            [scaleImagesArr addObject:newImage];
        }
        self.editeImageHandle(scaleImagesArr);
    }
}

-(UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}

-(CIFilter *)filter
{
    if (_filter == nil)
    {
        //CISharpenLuminance*******CIUnsharpMask*********CIColorControls
        _filter = [CIFilter filterWithName:@"CIColorControls"];
    }
    return _filter;
}

-(CIContext *)context
{
    if (_context == nil)
    {
//        EAGLContext *egc = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
//        _context = [CIContext contextWithEAGLContext:egc];
        _context = [CIContext contextWithOptions:nil];
    }
    return _context;
}

-(NSMutableArray *)snapImagesArr
{
    if (_snapImagesArr == nil)
    {
        _snapImagesArr = [NSMutableArray array];
    }
    return _snapImagesArr;
}

-(NSMutableArray *)changedArr
{
    if (_changedArr == nil)
    {
        _changedArr = [NSMutableArray array];
    }
    return _changedArr;
}
-(NSMutableDictionary *)filterDescriptorsDict
{
    if (_filterDescriptorsDict == nil)
    {
        _filterDescriptorsDict = [NSMutableDictionary dictionary];
    }
    return _filterDescriptorsDict;
}

-(void)getDefaultValueAgain
{
    NSArray *inputNames = self.filter.inputKeys;
    NSDictionary *attributes = self.filter.attributes;
    
    for (NSString *inputName in inputNames)
    {
        if ([inputName isEqualToString:@"inputImage"])
        {
            continue;
        }
        NSDictionary *dict = attributes[inputName];
        CGFloat defaultValue = [dict[kCIAttributeDefault] floatValue];
        
        [self.filterDescriptorsDict setObject:@(defaultValue) forKey:inputName];
    }
}

@end
